<template>
  <el-form :model="form" ref="form" size="small" label-width="120px" label-position="right">
    <div class="flex align-center">
      <div class="method-title flex-shrink-0 text-right" style="width:80px">{{getTypeName2(feeMode)}}</div>
      <div class="flex-1">
        <div v-for="(item, index) in form.list" :key="item.uuid" class="flex">
          <!-- 起始值 -->
          <template v-if="feeMode === 'pieces'">
            <el-form-item :label="index === 0 ? getTypeName3(feeMode) : getTypeName4(feeMode) + index" label-width="90px" :prop="`list.${index}.intStart`"
                          :rules="{
              required: true, validator: validateStart, trigger: 'change' }"
            >
              <el-input
                @input="limitInput($event, 'intStart', index)"
                v-model="item.intStart"
                :disabled="index === 0"
                clearable
                style="width:120px"
                placeholder="请输入"
              /> {{getTypeName5(feeMode)}}
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item :label="index === 0 ? getTypeName3(feeMode) : getTypeName4(feeMode) + index" label-width="90px" :prop="`list.${index}.floatStart`"
                          :rules="{
              required: true, validator: validateStart, trigger: 'change' }"
            >
              <el-input
                @input="limitInput($event, 'floatStart', index)"
                v-model="item.floatStart"
                disabled
                clearable
                style="width:120px"
                placeholder="请输入"
              /> {{getTypeName5(feeMode)}}
            </el-form-item>
          </template>
          <el-form-item class="ml5" v-if="index !== form.list.length - 1" label="" label-width="0">
            ~
          </el-form-item>
          <!-- 终止值 -->
          <template v-if="feeMode === 'pieces'">
            <el-form-item v-if="index !== form.list.length - 1" class="ml10" label="" label-width="0" :rules="{
              required: true, validator: (rule, value, callback) => validateEnd(rule, value, callback, item, 'intStart'), trigger: 'blur' }" :prop="`list.${index}.intEnd`"
            >
              <el-input
                @input="onInputMax(index, $event, feeMode, 'intEnd')"
                v-model="item.intEnd"
                clearable
                style="width:120px"
                placeholder="请输入"
              /> {{getTypeName5(feeMode)}}
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item v-if="index !== form.list.length - 1" class="ml10" label="" label-width="0"  :rules="{
              required: true, validator: (rule, value, callback) => validateEnd(rule, value, callback, item, 'floatStart'), trigger: 'blur' }" :prop="`list.${index}.floatEnd`"
            >
              <el-input
                @input="onInputMax(index, $event, feeMode, 'floatEnd')"
                v-model="item.floatEnd"
                clearable
                style="width:120px"
                placeholder="请输入"
              /> {{getTypeName5(feeMode)}}
            </el-form-item>
          </template>
          <!-- 价格 -->
          <el-form-item class="ml30" :label="getTypeName6(index)" label-width="70px"  :rules="{
            required: true, validator: validatePrice, trigger: 'blur' }" :prop="`list.${index}.price`"
          >
            <el-input
              @input="limitInput_price($event, 'price', index)"
              v-model="item.price"
              clearable
              style="width:120px"
              placeholder="请输入"
            /> 元 / 每公里*吨
          </el-form-item>
          <el-form-item label="" label-width="0" class="ml5">
            <i class="el-icon-circle-plus-outline mr5 font-size20 pointer primary-color " v-if="index !== form.list.length - 1" @click="handleAdd(index, feeMode)"></i>
            <i class="el-icon-remove-outline font-size20 pointer primary-color "  v-if="index !== 0 && index !== form.list.length - 1"  @click="handleDelete(index, feeMode)"></i>
          </el-form-item>
        </div>
      </div>
    </div>
  </el-form>
</template>

<script>
import { randomString } from "@/utils/zito"
export default {
  props: {
    data: {
      type: Array,
      default: () => []
    },
    feeMode: {
      type: String,
      default: 'mileage'
    },
  },
  data() {
    return {
      form: {
        list: this.data
      },
      options: []
    };
  },
  watch: {
    data: {
      handler(val) {
        this.form.list = val || []
      },
    },
  },
  methods: {
    validateStart(rule, value, callback) {
      if (value === '') {
        callback(new Error('起始值不能为空'));
      } else if (isNaN(+value)) {
        callback(new Error('请输入数字'))
      } else {
        callback()
      }
    },
    validateEnd(rule, value, callback, item, name) {
      if (value === '') {
        callback(new Error('终止值不能为空'));
      } else if (isNaN(+value)) {
        callback(new Error('请输入数字'))
      } else if (+value <= item[name]) {
        callback(new Error('终止值必须大于起始值'));
      } else {
        callback()
      }
    },
    validatePrice(rule, value, callback) {
      if (!value && value !== 0) {
        callback(new Error('价格不能为空'));
      } else if (value === 0) {
        callback(new Error('价格必须大于0'));
      } else {
        callback()
      }
    },
    getTypeName(type) {
      return {
        mileage: '按里程',
        weight: '按重量',
        volume: '按体积',
        pieces: '按件数',
        volumeWeight: '按体积重量',
        weightMultiMileage: '按重量里程',
      }[type] || ''
    },
    getTypeName2(type) {
      return {
        mileage: '实际里程',
        weight: '实际重量',
        volume: '实际体积',
        pieces: '实际件数',
        volumeWeight: '体积重量',
        weightMultiMileage: '重量里程',
      }[type] || ''
    },
    getTypeName3(type) {
      return {
        mileage: '首里程',
        weight: '首重',
        volume: '首容量',
        pieces: '首件',
        volumeWeight: '首重',
        weightMultiMileage: '首重',
      }[type] || ''
    },
    getTypeName4(type) {
      return {
        mileage: '续里程',
        weight: '续重',
        volume: '续容量',
        pieces: '续件',
        volumeWeight: '续重',
        weightMultiMileage: '续重',
      }[type] || ''
    },
    getTypeName5(type) {
      return {
        mileage: 'KM',
        weight: '吨',
        volume: '立方',
        pieces: '件',
        volumeWeight: '吨',
        weightMultiMileage: '吨',
      }[type] || ''
    },
    getTypeName6(index) {
      return index === 0 ? '起运价' : '叠加价'
    },

    handleAdd(index, feeMode) {
      Promise.all(this.form.list.map(async (item, index) => {
        let validate = ''
        this.$refs.form.validateField([`list.${index}.${feeMode === 'pieces' ? 'intEnd' : 'floatEnd'}`, `list.${index}.${feeMode === 'pieces' ? 'intStart' : 'floatStart'}`], err => {
          validate = err
        })

        return validate
      })).then(res => {
        const find = res.find(item => item !== '')

        if (!find) {
          let params = {}

          if (feeMode === 'pieces') {
            params.intStart = this.form.list[index].intEnd
          } else {
            params.floatStart = this.form.list[index].floatEnd
          }

          this.form.list.splice(index+1, 0, { feeMode: this.feeMode, uuid: randomString(32), ...params})
          this.$set(this.form.list[this.form.list.length - 1], feeMode === 'pieces' ? 'intStart' : 'floatStart', '')
        }
      })
    },

    handleDelete(index, feeMode) {
      let list = this.form.list
      this.form.list.splice(index, 1)

      if (list[index - 1]) this.$set(this.form.list[index], 'floatStart', this.form.list[index - 1][feeMode === 'pieces' ? 'intEnd' : 'floatEnd'])
    },

    // 监听输入框
    async onInputMax(index, value, feeMode, name) {
      await this.limitInput(value, name, index)
      this.$set(this.form.list[index + 1], `${feeMode === 'pieces' ? 'intStart' : 'floatStart'}`, this.form.list[index][name])
    },

    // 小数点后2个0
    limitInput(value,name, index) {
      this.form.list[index][name] = ('' + value) // 第一步：转成字符串
        .replace(/[^\d^\.]+/g, '') // 第二步：把不是数字，不是小数点的过滤掉
        .replace(/^0+(\d)/, '$1') // 第三步：第一位0开头，0后面为数字，则过滤掉，取后面的数字
        .replace(/^\./, '0.') // 第四步：如果输入的第一位为小数点，则替换成 0. 实现自动补全
        .match(/^\d*(\.?\d{0,3})/g)[0] || '' // 第五步：最终匹配得到结果 以数字开头，只有一个小数点，而且小数点后面只能有0到2位小数
    },

    limitInput_price(value, name, index) {
      this.form.list[index][name] = ('' + value) // 第一步：转成字符串
        .replace(/[^\d^\.]+/g, '') // 第二步：把不是数字，不是小数点的过滤掉
        .replace(/^0+(\d)/, '$1') // 第三步：第一位0开头，0后面为数字，则过滤掉，取后面的数字
        .replace(/^\./, '0.') // 第四步：如果输入的第一位为小数点，则替换成 0. 实现自动补全
        .match(/^\d*(\.?\d{0,2})/g)[0] || '' // 第五步：最终匹配得到结果 以数字开头，只有一个小数点，而且小数点后面只能有0到2位小数
    },

    async handleValidate() {
      try {
        await this.$refs.form.validate()
        return Promise.resolve(true)
      } catch (error) {
        return Promise.resolve(false)
      }
    },
  }
};
</script>
<style lang="scss">
.method-title {
  position: relative;
  top: -10px;
}
</style>
